
const { test111Config } = require("../../config")

const { jdbcUtils } = require("../../utils/jdbcUtils")

const { DB_ERROR, TB_USER_IS_EXIST } = require("../../domain/constance")

class UserDao {

    constructor() {
        this.currentConnetion = null
        this.isConnected = false;
        this.currentConnetion = jdbcUtils.getConnection(test111Config)
    }

    async checkConnected() {
        if (this.isConnected) return
        return await this.connect()
    }

    connect() {
        // 建立连接
        return new Promise((resolve, reject) => {
            if (this.currentConnetion) {
                this.currentConnetion.connect(error => {
                    if (error) reject(`${DB_ERROR}: ${error.message}`)
                    this.isConnected = true
                    resolve()
                })
            } else {
                // 重新创建连接
                this.currentConnetion = jdbcUtils.getConnection(test111Config)
                this.isConnected = true;
                resolve()
            }
        })
    }

    // 获取全部用户信息
    getTbUsers() {
        return this.baseDao(`select * from tb_user`)
    }

    getTbUserByName(username, password) {
        return this.baseDao(`select * from tb_user where name='${username}' and password='${password}'`)
    }

    getTbUserByEmail(email, password) {
        return this.baseDao(`select * from tb_user where email='${email}' and password='${password}'`)
    }

    // 更新用户信息
    update(tbUser) {
        let sql = `update tb_user set`;
        let keys = Object.keys(tbUser);
        const len = keys.length;
        for (let i = 0; i < len; ++i) {
            if (keys[i] === 'id') continue
            sql += ` ${keys[i]}='${tbUser[keys[i]]}'`
            if (i === len - 1) continue
            sql += ` , `
        }
        sql += ` where id = ${+tbUser.id}`

        return this.baseDao(sql)
        // try {
        //     return await this.baseDao(sql);

        // } catch (error) {
        //     if (error.includes('ER_DUP_ENTRY')) {
        //         // 这里只捕获 插入异常 
        //         return Promise.resolve(TB_USER_IS_EXIST)
        //     }

        // }
    }

    // 通用的 query
    async baseDao(sql) {
        // 阻塞等待 检查连接
        await this.checkConnected()
        // 等待 query 的回调结果 
        return new Promise((resolve, reject) => {
            this.currentConnetion.query(sql,
                async (error, results) => {
                    if (error) {
                        if (error.message.includes("ER_DUP_ENTRY")) {
                            resolve(TB_USER_IS_EXIST)
                        }
                        reject(`${DB_ERROR}: ${error.message}`)
                    }
                    resolve(results)
                })
        })
    }

    // 插入用户信息
    insert(tbUser) {
        return this.baseDao(`insert into tb_user(name, nickname, password) values('${tbUser.name}', '${tbUser.nickname}', '${tbUser.password}')`)
    }

    // 删除
    delete(id) {
        return this.baseDao(`delete from tb_user where id = ${id}`)
    }
}

module.exports = {
    UserDao
}